import React, { useEffect, useRef } from 'react';
import { jsapi, viewUtils } from '@/utils/arcgis';
import {
  initEchartsLayer,
  updateEchartsLayer,
  hideEchartsLayer,
  removeEchartsLayer,
} from '@/components/content/mainPage/chartLayer/flowRender';

export default function FlowMode({ isRenderFlow, layerId }) {
  const lyrRef = useRef<any>();

  useEffect(() => {
    if (!lyrRef.current) {
      console.error('没有选择流光图的目标图层');
      return;
    }
    handleFlowRender(layerId, isRenderFlow);
    return () => {};
  }, [isRenderFlow, layerId]);

  useEffect(() => {
    init(layerId);
    return () => {
      lyrRef.current = null;
      // removeEchartsLayer();
    };
  }, []);

  async function init(layerId) {
    const view = await viewUtils.isViewReady();
    setTimeout(() => {
      const lyr = view.map.findLayerById(layerId);
      lyrRef.current = lyr;
      initEchartsLayer([]);
    }, 600);
  }

  async function handleFlowRender(layerId, isRenderFlow) {
    const [webMercatorUtils] = await jsapi.load(['esri/geometry/support/webMercatorUtils']);
    const lyr = lyrRef.current;
    if (!lyr) {
      return;
    }
    const flowGeometry = [];
    // 每次都需要遍历来切换原有线的显隐
    lyr.graphics.items.forEach(e => {
      // console.log(e, e.attributes);

      const color = e.symbol.symbolLayers.items[0].material.color;
      const colorStr = `rgba(${color.r}, ${color.g}, ${color.b}, ${color.a})`;
      if (e.attributes && e.attributes.type) {
        // console.log(e.attributes.type);
        if (e.attributes.type === 'flow') {
          e.visible = !isRenderFlow;
          if (isRenderFlow) {
            const { paths } = webMercatorUtils.webMercatorToGeographic(e.geometry);
            // console.log(paths, '-=-=-=----------------===');
            flowGeometry.push(
              ...paths.map(e => {
                e.color = colorStr;
                // e.color = 'rgba(255,200,40,1)';
                return e;
              }),
            );
          }
        }
      }
    });

    // 切换echarts图层的显隐
    if (isRenderFlow) {
      updateEchartsLayer(flowGeometry);
    } else {
      hideEchartsLayer();
    }
    console.log(flowGeometry);
  }

  return (
    <>
      <h1></h1>
    </>
  );
}
